package com.hserver.deploy.utils;

import org.apache.commons.exec.*;

import java.io.*;
import java.util.Scanner;

/**
 *
 */
public class ShellUtil {

    public static String exec(CmdMsg msg, String... cmd) throws IOException {

        CommandLine cmdLine = CommandLine.parse(cmd[0]);
        for (int i = 1; i < cmd.length; i++) {
            if (StringUtils.hasText(cmd[i])) {
                cmdLine.addArgument(cmd[i], false);
            } else {
                cmdLine.addArgument("null", false);
            }
        }

        DefaultExecutor executor = new DefaultExecutor();

        // 防止抛出异常
        executor.setExitValues(null);

        // 命令执行的超时时间3小时自动介绍自己
        ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000 * 60 * 3);
        executor.setWatchdog(watchdog);

        if (msg != null) {
            PipedOutputStream os = new PipedOutputStream();
            PumpStreamHandler streamHandler = new PumpStreamHandler(os);
            executor.setStreamHandler(streamHandler);
            PipedInputStream is = new PipedInputStream(os);
            new Thread() {
                @Override
                public void run() {
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    while (true) {
                        try {
                            String s=br.readLine();
                            if (s!=null){
                                msg.result(s);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (!watchdog.isWatching()){
                            return;
                        }
                    }

                }
            }.start();
            executor.execute(cmdLine);
            return null;
        } else {

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
            executor.setStreamHandler(streamHandler);

            executor.execute(cmdLine);

            return outputStream.toString();
        }
    }
}
